package models

import (
	"time"

	"gorm.io/gorm"
)

// Friend 好友关系模型
type Friend struct {
	gorm.Model
	UserID    int       `json:"user_id" gorm:"not null"`
	FriendID  int       `json:"friend_id" gorm:"not null"`
	CreatedAt time.Time `json:"created_at"`
}

// FriendWithUserInfo 包含用户信息的好友结构
type FriendWithUserInfo struct {
	Friend
	FriendUserID     int    `json:"friend_user_id"`
	FriendUserName   string `json:"friend_user_name"`
	FriendUserEmail  string `json:"friend_user_email"`
	FriendUserAvatar string `json:"friend_user_avatar"`
}

func AddFriend(userID, friendID int) error {
	friend := &Friend{UserID: userID, FriendID: friendID, CreatedAt: time.Now()}
	return GetDB().Create(friend).Error
}

func GetFriends(userID int) ([]Friend, error) {
	var friends []Friend
	err := GetDB().Where("user_id = ?", userID).Find(&friends).Error
	return friends, err
}

// GetFriendsWithUserInfo 获取好友列表并包含用户信息
func GetFriendsWithUserInfo(userID int) ([]FriendWithUserInfo, error) {
	var friendsWithInfo []FriendWithUserInfo
	err := GetDB().Table("friends").
		Select("friends.*, users.id as friend_user_id, users.name as friend_user_name, users.email as friend_user_email, users.avatar as friend_user_avatar").
		Joins("LEFT JOIN users ON friends.friend_id = users.id").
		Where("friends.user_id = ?", userID).
		Find(&friendsWithInfo).Error
	return friendsWithInfo, err
}

func DeleteFriend(userID, friendID int) error {
	return GetDB().Where("user_id = ? AND friend_id = ?", userID, friendID).Delete(&Friend{}).Error
}
